package com.hnit.applet.utils;

import org.springframework.beans.BeanUtils;

import javax.sql.rowset.serial.SerialException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: class转换
 * @Author: chang_hy
 * @Date: 2022/4/7 15:05
 * @Versions 1.0.0
 **/
public class BeanHelper {

    public static <T> T copyProperties(Object source, Class<T> target) {
        try {
            if (source == null) throw new SerialException("参数拷贝异常");
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T copyProperties(List<T> source, Class<T> target, String... ignoreProperties) {
        try {
            if (source == null) throw new SerialException("参数拷贝异常");
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t, ignoreProperties);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> List<T> copyPropertyList(List<?> source, Class<T> target) {
        try {
            if (source == null) throw new SerialException("参数拷贝异常");
            return source.stream().map(list -> copyProperties(list, target)).collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static <T> Set<T> copyPropertySet(Set<?> source, Class<T> target) {
        try {
            if (source == null) throw new SerialException("参数拷贝异常");
            return source.stream().map(list -> copyProperties(list, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            e.printStackTrace();
            return new HashSet<>();
        }
    }
}
